package leetcode.string;

/**
 * 给定两个字符串形式的非负整数 num1 和num2 ，计算它们的和。
 * 提示：
 * <p>
 * num1 和num2 的长度都小于 5100
 * num1 和num2 都只包含数字 0-9
 * num1 和num2 都不包含任何前导零
 * 你不能使用任何內建 BigInteger 库， 也不能直接将输入的字符串转换为整数形式
 */
public class Add {

    public static String addStrings(String num1, String num2) {
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringBuilder1 = new StringBuilder(num1);
        StringBuilder stringBuilder2 = new StringBuilder(num2);

        stringBuilder1 = stringBuilder1.reverse();
        stringBuilder2 = stringBuilder2.reverse();

        int length = Math.max(stringBuilder1.length(), stringBuilder2.length()) - Math.min(stringBuilder1.length(), stringBuilder2.length());

        if (stringBuilder1.length() > stringBuilder2.length()) {
            for (int index = 0; index < length; index++) {
                stringBuilder2.append("0");
            }
        } else if (stringBuilder1.length() < stringBuilder2.length()) {
            for (int index = 0; index < length; index++) {
                stringBuilder1.append("0");
            }
        }

        int temp = 0;
        for (int index = 0; index < stringBuilder1.length(); index++) {
            temp = stringBuilder1.charAt(index) + stringBuilder2.charAt(index) + temp - 96;

            if (temp >= 10) {
                stringBuilder.append(temp - 10);
                temp = 1;
            } else {
                stringBuilder.append(temp);
                temp = 0;
            }
        }

        if (temp == 1){
            stringBuilder.append("1");
        }

        return stringBuilder.reverse().toString();
    }

}
